package github.kawaiior.botapiserver.interceptor;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import github.kawaiior.botapiserver.common.ActionResponse;
import github.kawaiior.botapiserver.entity.User;
import github.kawaiior.botapiserver.mapper.UserMapper;
import github.kawaiior.botapiserver.util.CookieUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

public class TokenInterceptor implements HandlerInterceptor {

    private final UserMapper userMapper;

    public TokenInterceptor(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    private final String VALID_TOKEN = JSONUtil.toJsonStr(new ActionResponse(-1, "valid token"));

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!isValidToken(request)) {

            String requestMethod = request.getMethod();
            String requestURI = request.getRequestURI();
            String requestIP = request.getRemoteAddr();

            logger.info("{} - {} - {} - valid token !", requestIP, requestMethod, requestURI);
            response.getWriter().write(VALID_TOKEN);
            return false;
        }

        return true;
    }

    private boolean isValidToken(HttpServletRequest request) {
        String token = CookieUtil.getCookieValueByKey("token", request);
        String account = CookieUtil.getCookieValueByKey("account", request);

        if ("".equals(token)){
            return false;
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account)
                .eq(User::getToken, token);
        User user = userMapper.selectOne(queryWrapper);
        return user != null;
    }

}

